package com.cande.loki.exercise.manythread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @auther ROCK CODER
 * @DATE 2022/4/4 10:33
 * @Description 这个是淘宝面试题比较好的解决方案
 */
public class TaoBaogood {


    volatile List list = new ArrayList();

    public void add(Object o) {
        list.add(o);
    }

    public int size() {
        return list.size();
    }

    public static void main(String[] args) {
        final Object o = new Object();
        CountDownLatch latch = new CountDownLatch(1);
        TaoBaogood taobaogood = new TaoBaogood();

        new Thread(() -> {
            if (taobaogood.size() < 5) {
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("t2 is over");
            }
        }, "t2").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {

                taobaogood.add(new Object());

                System.out.println("t1:" + i);
                if (i == 4) {
                    latch.countDown();
                }
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }

        }, "t1").start();
    }
}


